package com.zmn.plat.business.impl.service.tariff.citygroup;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.plat.business.interfaces.service.tariff.citygroup.ServiceTariffCityGroupBService;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.entity.service.tariff.citygroup.ServiceTariffCityGroup;
import com.zmn.plat.model.entity.service.tariff.citygroup.ServiceTariffCityGroupQuery;
import com.zmn.plat.model.entity.service.tariff.citygroup.item.ServiceTariffCityGroupItem;
import com.zmn.plat.model.entity.service.tariff.citygroup.item.ServiceTariffCityGroupItemQuery;
import com.zmn.plat.model.vo.service.tariff.citygroup.ServiceTariffCityGroupAddEditVO;
import com.zmn.plat.model.vo.service.tariff.citygroup.ServiceTariffCityGroupVO;
import com.zmn.plat.services.interfaces.service.tariff.citygroup.ServiceTariffCityGroupService;
import com.zmn.plat.services.interfaces.service.tariff.citygroup.item.ServiceTariffCityGroupItemService;

/**
 * @author tanbiao
 * @description
 * @since 2020/5/28 15:05
 * @modifier
 **/
@Service
public class ServiceTariffCityGroupBServiceImpl implements ServiceTariffCityGroupBService {
    @Resource
    private ServiceTariffCityGroupService faultCityGroupService;
    @Resource
    private ServiceTariffCityGroupItemService faultCityGroupItemService;

    @Override
    public List<ServiceTariffCityGroupVO> listPageQuery(ServiceTariffCityGroupQuery query) {
        List<ServiceTariffCityGroupVO> retList = new ArrayList<>();
        List<ServiceTariffCityGroup> list = faultCityGroupService.listPageByQuery(query);
        if (!CollectionUtils.isEmpty(list)) {
            ServiceTariffCityGroupItemQuery itemQuery = new ServiceTariffCityGroupItemQuery();
            BeanCopier copier = BeanCopier.create(ServiceTariffCityGroupQuery.class, ServiceTariffCityGroupItemQuery.class, false);
            copier.copy(query, itemQuery, null);
            List<ServiceTariffCityGroupItem> itemList = faultCityGroupItemService.listByQuery(itemQuery);
            if (!CollectionUtils.isEmpty(itemList)) {
                BeanCopier groupCopy = BeanCopier.create(ServiceTariffCityGroup.class, ServiceTariffCityGroupVO.class, false);
                Map<Integer, StringBuilder> cityNameMap = new HashMap<>();
                for (ServiceTariffCityGroupItem groupItem : itemList) {
                    StringBuilder name = cityNameMap.get(groupItem.getGroupId());
                    if (Objects.isNull(name)) {
                        name = new StringBuilder(groupItem.getCityName()).append(",");
                    } else {
                        name.append(groupItem.getCityName()).append(",");
                    }
                    cityNameMap.put(groupItem.getGroupId(), name);
                }
                for (ServiceTariffCityGroup group : list) {
                    ServiceTariffCityGroupVO vo = new ServiceTariffCityGroupVO();
                    groupCopy.copy(group, vo, null);
                    vo.setCityNames("");
                    StringBuilder name = cityNameMap.get(vo.getGroupId());
                    if (null != name) {
                        vo.setCityNames(name.deleteCharAt(name.length() - 1).toString());
                    }
                    retList.add(vo);
                }
            }
        }
        return retList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addEdit(ServiceTariffCityGroupAddEditVO faultGroup, String mcStaffRealName) {
        // 公共信息
        Integer groupId = faultGroup.getGroupId();
        Integer tariffId = faultGroup.getTariffId();
        Integer categOneId = faultGroup.getCategOneId();
        Integer servCategId = faultGroup.getServCategId();
        // 名称不能重复
        checkGroupName(groupId, servCategId, categOneId, tariffId, faultGroup.getGroupName());
        // 修改分组
        Date now = DateUtil.getNow();
        if (NumberUtil.isPositiveInteger(groupId)) {
            faultGroup.setUpdateTime(now);
            faultGroup.setUpdater(mcStaffRealName);
            faultCityGroupService.updateByKey(faultGroup);
            // 对于明细都删除在插入
            faultCityGroupItemService.deleteByGroupId(groupId);
        } else {
            // 新增分组
            faultGroup.setUpdateTime(now);
            faultGroup.setUpdater(mcStaffRealName);
            faultGroup.setCreateTime(now);
            faultGroup.setCreater(mcStaffRealName);
            faultCityGroupService.insert(faultGroup);
        }
        List<ServiceTariffCityGroupItem> cityGroupItems = faultGroup.getItemList().stream()
            .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ServiceTariffCityGroupItem::getCityId))), ArrayList::new));
        cityGroupItems.stream().forEach(e -> {
            e.setGroupId(faultGroup.getGroupId());
            e.setTariffId(tariffId);
            e.setCreateTime(now);
            e.setUpdateTime(now);
            e.setCreater(mcStaffRealName);
            e.setUpdater(mcStaffRealName);
            e.setCategOneId(categOneId);
            e.setServCategId(servCategId);
        });
        return faultCityGroupItemService.insertBatch(cityGroupItems);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteByKey(Integer groupId) {
        faultCityGroupItemService.deleteByGroupId(groupId);
        return faultCityGroupService.deleteByKey(groupId);
    }

    private void checkGroupName(Integer groupId, Integer servCategId, Integer categOneId, Integer tariffId, String groupName) {
        ServiceTariffCityGroupQuery query = new ServiceTariffCityGroupQuery();
        query.setCategOneId(categOneId);
        query.setServCategId(servCategId);
        query.setTariffId(tariffId);
        query.setGroupName(groupName);
        List<ServiceTariffCityGroup> groupList = faultCityGroupService.listByQuery(query);
        if (!CollectionUtils.isEmpty(groupList)) {
            // 同名的分组大于1或者是新增但是存在同名的分组
            if (groupList.size() > 1 || NumberUtil.isNullOrZero(groupId)) {
                throw new PlatException("同一价格表同一服务分类同一后台一级分类下的城市分组名称不能重复");
            } else {
                // 修改
                if (NumberUtil.isPositiveInteger(groupId)) {
                    ServiceTariffCityGroup group = groupList.get(0);
                    if (!Objects.equals(group.getGroupId(), groupId)) {
                        throw new PlatException("同一价格表同一服务分类同一后台一级分类下的城市分组名称不能重复");
                    }
                }
            }
        }
    }
}
